<?php
namespace app\api\service;

use think\Controller;
use think\facade\Env;

use Stripe\Stripe;
use Stripe\Customer;
use Stripe\Charge;
use Stripe\Token;

/**
 * Stripe 支付
 * @author sam
 * Date 2019/07/22
 */
class Paystripe extends Controller
{

    private $stripe = '';

    public function __construct()
    {   
        parent::__construct();

        $config  = config("logic.stripe_config");
        $this->stripe = new Stripe();
        $this->stripe::setApiKey($config['secret_key']);
    }

    /**
     * Creates a charge.
     * @param      <intval>  $amount      The amount
     * @param      <string>  $currency    The currency
     * @param      <string>  $customerId  The customerId
     * @return     array  (response of request)
     */
    public function createCharge($amount, $currency, $customerId)
    {
        $chargeObj = new Charge();
        try {
            $charge = $chargeObj::create([
                'amount'   => $amount,
                'currency' => $currency,
                'customer' => $customerId,
            ]);
        } catch(\Stripe\Error\Card $e) {
            // Since it's a decline, \Stripe\Error\Card will be caught
        } catch (\Stripe\Error\RateLimit $e) {
            // Too many requests made to the API too quickly
        } catch (\Stripe\Error\InvalidRequest $e) {
            // Invalid parameters were supplied to Stripe's API
        } catch (\Stripe\Error\Authentication $e) {
            // Authentication with Stripe's API failed
        } catch (\Stripe\Error\ApiConnection $e) {
            // Network communication with Stripe failed
        } catch (\Stripe\Error\Base $e) {
            // Display a very generic error to the user, and maybe send yourself an email
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
        }

        // Thrown exception
        if (!empty($e) && is_object($e)) {
            $body = $e->getJsonBody();
            $err  = $body['error'];
            return $err;
        }else{
            return $charge;
        }

    }

    /**
     * Creates a token.
     * @param      <string>  $source   The source
     * @param      <string>  $email    The email
     * @return     <array>  (response of request)
     */
    public function createCustomer($source)
    {
        $customerObj = new Customer();
        try {
            $customer = $customerObj::create([
                'source' => $source,
            ]);
        } catch(\Stripe\Error\Card $e) {
            // Since it's a decline, \Stripe\Error\Card will be caught
        } catch (\Stripe\Error\RateLimit $e) {
            // Too many requests made to the API too quickly
        } catch (\Stripe\Error\InvalidRequest $e) {
            // Invalid parameters were supplied to Stripe's API
        } catch (\Stripe\Error\Authentication $e) {
            // Authentication with Stripe's API failed
        } catch (\Stripe\Error\ApiConnection $e) {
            // Network communication with Stripe failed
        } catch (\Stripe\Error\Base $e) {
            // Display a very generic error to the user, and maybe send yourself an email
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
        }

        // Thrown exception
        if (!empty($e) && is_object($e)) {
            $body = $e->getJsonBody();
            $err  = $body['error'];
            return $err;
        }else{
            return $customer;
        }

    }

    /**
     * Creates a token.
     * @param      Array  $card   card info
     * @return     array  (response of request)
     */
    public function createToken($card)
    {
        $tokenObj = new Token();
        try {
            $token = $tokenObj::create([
                'card' => $card
            ]);
        } catch(\Stripe\Error\Card $e) {
            // Since it's a decline, \Stripe\Error\Card will be caught
        } catch (\Stripe\Error\RateLimit $e) {
            // Too many requests made to the API too quickly
        } catch (\Stripe\Error\InvalidRequest $e) {
            // Invalid parameters were supplied to Stripe's API
        } catch (\Stripe\Error\Authentication $e) {
            // Authentication with Stripe's API failed
        } catch (\Stripe\Error\ApiConnection $e) {
            // Network communication with Stripe failed
        } catch (\Stripe\Error\Base $e) {
            // Display a very generic error to the user, and maybe send yourself an email
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
        }

        // Thrown exception
        if (!empty($e) && is_object($e)) {
            $body = $e->getJsonBody();
            $err  = $body['error'];
            return $err;
        }else{
            return $token;
        }

    }

    
    /**
     * payment with button
     */
    public function custom()
    {

        $stripe = new Stripe();
        $stripe::setApiKey($this->secretKey);

        $session = \Stripe\Checkout\Session::create([
            'payment_method_types'       => ['card'], //支付方式
            'submit_type'                => 'donate', //事务类型
            'customer_email'             => 'customer@example.com', //客户邮箱
            'billing_address_collection' => 'required', //是否手机客户账单地址
            'line_items'                 => [[ //商品清单
                'name'        => 'Maserati',
                'description' => 'Maserati Quattroporte',
                'images'      => ['https://example.com/t-shirt.png'],
                'amount'      => "1332",
                'currency'    => 'usd',
                'quantity'    => 2,
            ]],
            'success_url' => $this->returnUrl,
            'cancel_url'  => $this->cancelUrl,
        ]);

        $data = json_decode(json_encode($session), true);

        $this->assign("data", $data);
        return $this->fetch();
    }

}
